import { useEffect, useRef } from "react";
import * as echarts from "echarts";

interface EchartsProps {
  options: any;
  width?: string;
  height?: string;
}

const EChartsComponent = ({
  options,
  width = "100%",
  height = "280px",
}: EchartsProps): React.ReactElement => {
  const chartRef = useRef(null);
  let chartInstance: null | echarts.EChartsType = null;
  useEffect(() => {
    if (chartRef.current) {
      chartInstance = echarts.init(chartRef.current);
      chartInstance.setOption(options);
      // 监听窗口变化
      window.addEventListener("resize", onResize);
      return () => {
        // 组件卸载时清楚监听器
        window.removeEventListener("resize", onResize);
        // 清除图表实例，避免内存泄漏
        chartInstance?.dispose();
      };
    }
  }, [options]);

  const onResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  return <div ref={chartRef} style={{ width: width, height: height }} />;
};

export default EChartsComponent;
